from datetime import datetime
# from matplotlib import pyplot as plt
# import csv
import cv2
# import numpy as np
# import pandas as pd
import sys


# For input capture device
device_id = int(sys.argv[1])

# /dev/video{device_id} normally
# 0 (if capture card connects when boot)
# 2 (if capture card connects after boot)s
if device_id >= 0:
    cam = cv2.VideoCapture(device_id)

else:
    # cam = cv2.VideoCapture(
    # '/home/smartwatchdog/Desktop/vaapp/test_video/2021-07-19 17-06-46.mkv'
    # )
    cam = cv2.VideoCapture(
        '/home/smartwatchdog/Desktop/vaapp/test_video/swd_atsmmi_20220127.mp4'
    )

# Print status
print(cam.isOpened())

# Set variables
cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
fps = cam.get(cv2.CAP_PROP_FPS)
print('fps: ', fps)

dimension = (cam.get(cv2.CAP_PROP_FRAME_WIDTH),
             cam.get(cv2.CAP_PROP_FRAME_HEIGHT))
print('dimension: ', dimension)

# Initialization of variable
frame_counter = 0  # For counting #frame recorded
filemax = 15*60*fps  # Start a new recording file every 15min


# Open the file for logging changes of point position
now = datetime.now()
dt_string = now.strftime("%Y%m%d%H%M%S")

# Export video
file_name = "/media/swd/Local Disk 1/recordings/output_{}.avi".format(dt_string)
# file_name = "/media/swd/My Passport/SWD_20230202/output_{}.avi".format(
#    dt_string)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# fourcc = cv2.VideoWriter_fourcc(*'YUYV')
out = cv2.VideoWriter(file_name, fourcc, fps, (1920, 1080))

# Start video processing
while cam.isOpened():

    # Read frames
    ret, img = cam.read()

    # Exit if no return
    if not ret:
        break

    frame = img.copy()

    # Current timestamp
    now = datetime.now()
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")

    # Output frame
    out.write(frame)
    cv2.imshow("Smart Watchdog Output", frame)

    frame_counter += 1

    if frame_counter == filemax:
        frame_counter = 0
        now = datetime.now()
        dt_string = now.strftime("%Y%m%d%H%M%S")

        out.release()

        file_name = "/media/swd/Local Disk 1/recordings/output_{}.avi".format(dt_string)
        #file_name = \
        #    "/media/swd/My Passport/SWD_20230202/output_{}.avi".format(
        #        dt_string
        #    )
        # fourcc = cv2.VideoWriter_fourcc(*'X264')
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        # fourcc = cv2.VideoWriter_fourcc(*'YUYV')
        out = cv2.VideoWriter(file_name, fourcc, fps, (1920, 1080))

    else:
        pass

    # Action on key press
    key = cv2.waitKey(1) & 0xFF

    if key == 27 or key == 113 or key == 81:
        # press ESC, Q or q to escape (ESC ASCII value: 27, Q: 81, q: 113)
        print("Escape hit, closing...")
        break
    elif key == 32:
        # press Space to capture image (Space ASCII value: 32)
        now = datetime.now()
        dt_string = now.strftime("%Y%m%d%H%M%S")
        img_name = \
            "/media/swd/Local Disk 1/screenshots/opencv_frame_{}.png".format(dt_string)
        #img_name = \
        #    "/media/swd/My Passport/SWD_20230202/opencv_frame_{}.png".format(
        #        dt_string
        #    )
        cv2.imwrite(img_name, img)  # define which image to be captured

        # hsv_crop = hsv[y_s[0]:y_s[0]+delta_ys, x_s[0]:x_s[0]+delta_xs]
        # h_hue = cv2.calcHist([hsv_crop], [0], None, [180], [0,180])
        # plt.subplot(111), plt.plot(h_hue)
        # plt.xlim([0,180])

        # plt.show()

    else:
        pass

# Release of resources
cam.release()
out.release()
cv2.destroyAllWindows()
